package com.hrbxlh.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.commons.CommonsMultipartFile;


/**
* -------------------------------------------------------
* Copyright (c) 2017, 鑫联华信息科技股份有限公司
* All rights reserved.
* FileName：FileUpload.java
* Description：文件上传util类。
* History：
* Date           Author               Desc
* 2017.3.28		  xzx                 建立
* -------------------------------------------------------
*/

public class FileUpload {
	
	/***@description 上传文件的方法
	 * @param 文件流
	 * @param 文件新名字
	 * @param 文件保存位置
	 * @return boolean true成功，false失败
	 * @throws Exception
	 */
	public Map<String,Object> fileUpload(CommonsMultipartFile file, String newName, String filePath) throws Exception{
		
		//20170622商莹将这个方法返回值改为map类型
		Map<String,Object> uploadMap = new HashMap<String,Object>();
		String resultPdf="";
		String resultDoc="";
		try{
			String fileOriginalName =  file.getOriginalFilename();
			System.out.println("fileOriginalName"+fileOriginalName);
			String extArr [] = fileOriginalName.split("\\.");
			if(!fileOriginalName.equals("")){
				String path = filePath + "/" + newName;
				//判断文件夹存不存在,不存在就创建
				File saveFile = new File(path);
				if (!saveFile.exists()) {
					File saveFileDir = new File(path.substring(0,path.lastIndexOf("\\") + 1));
					saveFileDir.mkdirs();
					saveFile = new File(path);
				}
				String filePdf = String.valueOf(saveFile);
				FileUtils.copyInputStreamToFile(file.getInputStream(), saveFile);
				resultPdf = newName;
				if(extArr[1].equals("pdf")){
					//说明上传的是pdf可以转成word文档，如果是视频的话就不可以了
					String wordpath = filePath + "/" + extArr[0]+".doc";
					resultDoc = extArr[0]+".doc";
					File saveWordFile = new File(wordpath);
					if (!saveWordFile.exists()) {
						File saveWordFileDir = new File(wordpath.substring(0,path.lastIndexOf("\\") + 1));
						saveWordFileDir.mkdirs();
						saveWordFile = new File(wordpath);
					}
					String fileWord = String.valueOf(saveWordFile);
					System.out.println("saveWordFile"+saveWordFile);
					//将pdf转为word
					readPdf(filePdf,fileWord);
				}
			}
			uploadMap.put("result", resultPdf);
			uploadMap.put("resultDoc", resultDoc);
			System.out.println("resultDoc"+resultDoc);
		}catch(Exception e){
			throw e;
		}
		return uploadMap;
	}
	
	/***@description 将pdf转为word
	 * @param pdf文件
	 * @param 路径
	 * @throws Exception
	 */
	public  void readPdf(String file,String wordPath)

	       throws DocumentException, IOException {
		FileOutputStream  fike = new FileOutputStream(wordPath);
	       PrintWriter writer = new PrintWriter(fike);//doc文件写入流

	       inspect(writer,file); //调用读取方法
	       
	       writer.close();
	       fike.close();

	   }
	   
	/***@description 将pdf转为word
	 * @param pdf文件
	 * @param 路径
	 * @throws Exception
	 */
	public  void inspect(PrintWriter writer, String filename)

	       throws IOException {

	       PdfReader reader = new PdfReader(filename); //读取pdf所使用的输出流

	       int num = reader.getNumberOfPages();//获得页数
	       System.out.println("页数"+num);
	       String content = "";  //存放读取出的文档内容

	       for (int i = 1; i <= num; i++) {
	    	  
	          content += PdfTextExtractor.getTextFromPage(reader, i); //读取第i页的文档内容
	         
         }

	      writer.write(content);//写入文件内容
	      reader.close();
	      writer.flush();
	      writer.close();

	   }
	
	/***
	 * @description 删除某文件
	 * @param 文件路径(最后一级要加"/")
	 * @param 文件名
	 * @return 成功失败
	 */
	public boolean deleteFileOnly(String path,String fileName)throws Exception {
		
		boolean result = false;
		try{
			File file = new File(path+fileName);
			if(file.isFile()){
				file.delete();
			}
			result = true;
		}catch(Exception e){
			throw e;
		}
		return result;
	}
	
	/***@description 构建上传文件的参数，并将文件上传
	 * @param 文件流
	 * @param request
	 * @return String 文件名
	 * @throws Exception
	 */
	public Map<String,Object> fileUploadParam(CommonsMultipartFile file, HttpServletRequest request) throws Exception{
		
		//20170622商莹将这个方法返回值改为map类型
		Map<String,Object> uploadMap = new HashMap<String,Object>();
		RandomValue random = new RandomValue();
		try{
			String fileOriginalName =  file.getOriginalFilename();
			String fileNamePre = random.getRandomValue(4, 4);
			String fileNameZD = fileNamePre + fileOriginalName.split("\\.")[0] +"."+ fileOriginalName.split("\\.")[fileOriginalName.split("\\.").length-1].toLowerCase();
			System.out.println("fileNameZD"+fileNameZD);
			String filePath = request.getSession().getServletContext().getRealPath("/upload/course");
			System.out.println("filePath"+filePath);
			uploadMap = this.fileUpload(file, fileNameZD, filePath);
		}catch(Exception e){
			throw e;
		}
		return uploadMap;
	}
	
	/***@description 删除课程上传的文件
	 * @param 文件流
	 * @param request
	 * @return 成功失败标识
	 * @throws Exception
	 */
	public boolean deleteFile(List<Map<String, Object>> chapterList,CommonsMultipartFile courseware,CommonsMultipartFile video,CommonsMultipartFile homework,CommonsMultipartFile courseMaterial,CommonsMultipartFile courseAnswer) throws Exception{
		
		boolean result = false;
		try{
			if(chapterList != null){
				if(chapterList.size() != 0){
					String[] keysArray = {"server_address", "project_name","tomcatUrl"};
					Map<String, Object> pathMap = ConfigFileUtil.getFileMessage("UtilFile.properties", keysArray);
					for(int i=0; i< chapterList.size(); i++){
						String path = (String)pathMap.get("tomcatUrl") + (String)pathMap.get("project_name")+"upload/course/";
						//修改的时候，没上传，就不删除文件
						if(!courseware.getOriginalFilename().equals("")){
							String coursewareName = (String)chapterList.get(i).get("coursewareName");
							this.deleteFileOnly(path, coursewareName);
						}
						if(!video.getOriginalFilename().equals("")){
							String videoName = (String)chapterList.get(i).get("videoName");
							this.deleteFileOnly(path, videoName);
						}
						if(!homework.getOriginalFilename().equals("")){
							String homeworkName = (String)chapterList.get(i).get("homeworkName");
							String homeworkNameDoc = (String) chapterList.get(i).get("homeworkNameDoc");
							this.deleteFileOnly(path, homeworkName);
							this.deleteFileOnly(path, homeworkNameDoc);
						}
						if(!courseMaterial.getOriginalFilename().equals("")){
							String courseMaterialName = (String)chapterList.get(i).get("courseMaterialName");
							this.deleteFileOnly(path, courseMaterialName);
						}
						if(!courseAnswer.getOriginalFilename().equals("")){
							String courseAnswerName = (String)chapterList.get(i).get("courseAnswerName");
							this.deleteFileOnly(path, courseAnswerName);
						}
					}
				}
			}
			result = true;
		}catch(Exception e){
			throw e;
		}
		return result;
	}
	
}
